const http = require('http')
const fs = require('fs')
const ws = require('socket.io')
const mysql = require('mysql')
const ulr = require('url')

const db = mysql.createPool({host: 'localhost', port: '3308', user: 'root', password: '', database: 'es6_talbe'})

const httpServer = http.createServer((req, res) => {
     let {pathname, query} = ulr.parse(req.url, true)
     if (pathname === '/register') {

          let { user, pass} = query
          if (!/^\w(6,32)$/.test(user)) {
               res.write(JSON.stringify({code: 1, msg: '用户名不符合规范'}))
               res.end()
          } else if (!/^.(6, 32)$/) {
               res.write(JSON.stringify({code: 1, msg: '密码不符合规范'}))
               res.end()
          } else {
               db.query(`SELECT * FROM user_table WHERE username='${user}'`, (error, data) => {
                    if (error) {
                         res.write(JSON.stringify({code: 1, msg: '数据库错了'}))
                         res.end()
                    } else {
                         if (data.length > 0) {
                              res.write(JSON.stringify({code: 1, msg: '用户已经存在'}))
                              res.end()
                         } else {
                              db.query(`INSERT INTO user_table (username, password, online) VALUES('${user}', '${pass}', 0)`, (errpr, data) => {
                                   if (error) {
                                        res.write(JSON.stringify({code: 1, msg: '数据库错了'}))
                                        res.end()
                                   } else {
                                        res.write(JSON.stringify({code: 0, msg: '注册成功'}))
                                        res.end()
                                   }
                              })
                         }
                    }
               })
          }

     } else if (pathname === '/login') {

     } else {
          fs.readFile(`./src/${req.url}`, (error, data) => {
               if (error) {
                    fs.readFile(`./http_error/404.html`, (error, data) => {
                         if (error) {
                              res.writeHead(404)
                              res.write('Not found')
                         } else {
                              res.writeHead(404)
                              res.write(data)
                         }
                         res.end()
                    })
               } else {
                    res.write(data)
                    res.end()
               }
          })
     }

})

ws.listen(httpServer)

httpServer.listen(2446)
console.log(`ws server running at http://localhost:2446`)